import itertools
import os
from flet import (
    FilePickerFileType,
    Column,
    Row,
    FilePicker,
    Dropdown,
    ElevatedButton,
    icons,
    dropdown,
    Text,
    Divider,
    Container,
    Icon,
    colors,
    Page,
    MainAxisAlignment,
    Theme,
    app,
    padding,
    Image,
    ImageFit,
    TextField,
    CrossAxisAlignment,
    SnackBar,
    OutlinedButton,
)
import toml
from xlsx_file import XlsxFile


class SplitStatGroup(Column):
    def __init__(
        self,
        page,
    ):
        super().__init__()
        self.page = page
        # self.handle_message = handle_message

        # self.handle_src_file = handle_src_file
        # self.handle_grade = handle_grade

        # self.handle_split = handle_split
        # self.handle_check = handle_check
        # self.handle_stat = handle_stat

        self.src_file = ""

    def on_read_config(self):
        with open("config.toml", "r", encoding="utf-8") as f:
            return f.read()
        
    def on_save_config(self):
        print('cf', self.config_text)
        with open("config.toml", "w", encoding="utf-8") as f:
            return f.write(self.config_textfield.value)

    def parse_config(self):

        config_dict = {'start_row': 2, 'keys': []}

        conf = toml.load("config.toml")
        print("handle_split", conf, self.src_file)
        for k,v in conf.items():
            if k == 'DEFAULT':
                if 'index' in v.keys():
                    config_dict['index'] = v.get('index')
                if 'start_row' in v.keys():
                    config_dict['start_row'] = v.get('start_row')
            
            if k[:4] == 'COL_':
                col = v.get('col')
                values = v.get('values')
                config_dict['keys'].append({'col': col, 'values': values})

        return config_dict

    def build(self):
        self.pick_src_file_dialog = FilePicker(on_result=self.pick_src_file_result)
        self.page.overlay.append(self.pick_src_file_dialog)

        self.selected_file = Text("未选择", size=12, color=colors.GREY_600)
        self.config_text = self.on_read_config()

        self.config_textfield = TextField(
                    multiline=True,
                    text_size=12,
                    min_lines=10,
                    max_lines=10,
                    label="配置",
                    value=self.config_text,
                )
        return Column(
            [
                Row(
                    [
                        Text("源文件", width=60),
                        OutlinedButton(
                            "选择",
                            icon=icons.UPLOAD,
                            on_click=lambda _: self.pick_src_file_dialog.pick_files(
                                file_type=FilePickerFileType.CUSTOM,
                                allowed_extensions=["xlsx"],
                            ),
                        ),
                    ]
                ),
                self.selected_file,
                self.config_textfield,
                Row(
                    [
                        ElevatedButton(
                            "保存配置",
                            icon=icons.EDIT_DOCUMENT,
                            on_click=lambda _: self.on_save_config(),
                        ),
                        ElevatedButton(
                            "拆分",
                            icon=icons.EDIT_DOCUMENT,
                            on_click=lambda _: self.handle_split(),
                        ),
                    ]
                ),
            ]
        )



    def get_cols_values(self, config_dict):
        cols = list(map(lambda x: x['col'], config_dict['keys']))
        values = list(map(lambda x: x['values'], config_dict['keys']))
        target_list = []

        for res in itertools.product(*values):
            target_list.append(res)

        return (cols, target_list)
    
    def handle_split(self):
        conf = self.parse_config()
        print("conf", conf)
        (cols, values) = self.get_cols_values(conf)
        print("cols", cols, "values", values)
        start_row = conf['start_row']
        index = None
        if 'index' in conf:
            index = conf['index']
        xlsx_file = XlsxFile([self.selected_file.value], cols,
                             values, start_row, index)
        xlsx_file.split()


    def pick_src_file_result(self, e):
        if e.files and len(e.files) > 0:
            self.src_file = e.files[0].path
            self.selected_file.value = self.src_file
            self.selected_file.update()

            print("aa", self.src_file)


class ResultGroup(Column):
    def __init__(self):
        super().__init__()
        self.target_file = ""

        self.result_text = Text("就绪", size=12, color=colors.GREY_600)
        self.open_button = ElevatedButton(
            "打开",
            icon=icons.OPEN_IN_NEW,
            on_click=lambda _: self.open_dir(),
            visible=False,
        )

        self.padding = padding.only(8, 0, 8, 0)

    def build(self):
        return Column(
            [
                Text("结果"),
                self.result_text,
                self.open_button,
            ]
        )

    def set_target_file(self, val):
        self.target_file = val
        self.result_text.value = val
        self.result_text.update()

        self.open_button.visible = True
        self.open_button.update()

    def open_dir(self):
        print("open dir", self.target_file, os.name)
        target_dir = os.path.dirname(self.target_file)

        if os.name == "nt":
            os.system(f"start {target_dir}")
        else:
            os.system(f"xdg-open {target_dir}")


def main(page: Page):
    page.title = "折分"
    page.vertical_alignment = MainAxisAlignment.START

    page.window.width = 900
    page.window.height = 580

    page.window.min_width = 900
    page.window.min_height = 580

    page.fonts = {
        "msyh": "C:\\Windows\\fonts\\msyh.ttc",
    }

    page.theme = Theme(font_family="msyh", color_scheme_seed=colors.BLUE)

    status_text = Text("")
    snack_bar = SnackBar(content=status_text)
    page.overlay.append(snack_bar)

    result_tip = ResultGroup()

    def show_msg(msg):
        status_text.value = msg
        page.snack_bar.open = True
        page.snack_bar.update()

    def split_book():
        print("# 拆分源表格")

        show_msg(f"完成\n结果在")

    page.add(
        Column(
            [
                Container(
                    padding=padding.only(8, 0, 8, 0),
                    content=SplitStatGroup(
                        page,
                    ),
                ),
                result_tip,
            ]
        )
    )


if __name__ == "__main__":
    print("加载中……")
    print("请稍候")
    app(target=main, assets_dir="assets")
